package com.fy.servlet;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.fy.dao.DaoFactory;
import com.fy.dao.NewsDao;
import com.fy.model.News;

@WebServlet("*.news")
public class NewsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String path = request.getRequestURI();
		NewsDao dao = DaoFactory.getNewsDao();
		if (path.contains("addui.news"))
			request.getRequestDispatcher("/WEB-INF/page/news/add.jsp").forward(request, response);
		else if (path.contains("add.news")) {
			String title = request.getParameter("title");
			String author = request.getParameter("author");
			String source = request.getParameter("source");
			String content = request.getParameter("content");
			News news = new News();
			news.setTitle(title);
			news.setAuthor(author);
			news.setSource(source);
			news.setContent(content);
			dao.insert(news);
			request.getRequestDispatcher("list.news").forward(request, response);
		} else if (path.contains("del.news")) {
			String newsid = request.getParameter("newsid");
			dao.delete(Integer.parseInt(newsid));
			request.getRequestDispatcher("list.news").forward(request, response);
		} else if (path.contains("updateui.news")) {
			String newsid = request.getParameter("newsid");
			News news = dao.findById(Integer.parseInt(newsid));
			request.setAttribute("news", news);
			request.getRequestDispatcher("/WEB-INF/page/news/update.jsp").forward(request, response);
		} else if (path.contains("update.news")) {
			String newsid = request.getParameter("newsid");
			String title = request.getParameter("title");
			String author = request.getParameter("author");
			String source = request.getParameter("source");
			String content = request.getParameter("content");
			News news = new News();
			news.setTitle(title);
			news.setAuthor(author);
			news.setSource(source);
			news.setContent(content);
			news.setNewsid(Integer.parseInt(newsid));
			dao.update(news);
			request.getRequestDispatcher("list.news").forward(request, response);
		} else if (path.contains("list.news")) {
			List<News> news = dao.find();
			request.setAttribute("news", news);
			request.getRequestDispatcher("/WEB-INF/page/news/list.jsp").forward(request, response);
		}
	}
}